AV.initialize('24HCDlOUHQNBCXzhPB24I21L', 'Cq3elz5UxtCdlgrmkQzzkLLH');
//全局變量定義
var JRSC_REG = AV.Object.extend("JRSC_REG");
var JRSC_MEMBERS = AV.Object.extend("JRSC_MEMBERS");
var Map = function() {
	this._entrys = new Array();

	this.put = function(key, value) {
		if (key == null || key == undefined) {
			return;
		}
		var index = this._getIndex(key);
		if (index == -1) {
			var entry = new Object();
			entry.key = key;
			entry.value = value;
			this._entrys[this._entrys.length] = entry;
		} else {
			this._entrys[index].value = value;
		}
	};
	this.get = function(key) {
		var index = this._getIndex(key);
		return (index != -1) ? this._entrys[index].value : null;
	};
	this.remove = function(key) {
		var index = this._getIndex(key);
		if (index != -1) {
			this._entrys.splice(index, 1);
		}
	};
	this.clear = function() {
		this._entrys.length = 0;;
	};
	this.contains = function(key) {
		var index = this._getIndex(key);
		return (index != -1) ? true : false;
	};
	this.getCount = function() {
		return this._entrys.length;
	};
	this.getEntrys = function() {
		return this._entrys;
	};
	this._getIndex = function(key) {
		if (key == null || key == undefined) {
			return -1;
		}
		var _length = this._entrys.length;
		for (var i = 0; i < _length; i++) {
			var entry = this._entrys[i];
			if (entry == null || entry == undefined) {
				continue;
			}
			if (entry.key === key) { //equal  
				return i;
			}
		}
		return -1;
	};
}

function getMembers(prodid) {
	var query = new AV.Query(JRSC_MEMBERS);

	query.select(["MEMBER_NAME,PROD_ID"]);
	query.ascending("MEMBER_NAME");
	//query.equalTo("PROD_ID", prodid);
	query.find().then(function(results) {
		if (results == undefined) {
			alert("产品线没有对应的人员列表，请联系管理员添加");
			return;
		}

		console.log("results" + results.length);
		var map = new Map();
		if (prodid == "4") { //zongti
			for (var i = 0; i < results.length; i++) {
				var object = results[i];
				if (object.get('PROD_ID') == prodid) {
					add_li(1 /*需要加入的li的個數*/ , switchProdName(object.get('PROD_ID')) /*需要加入的文本內容*/ , object.get('MEMBER_NAME') /*人名*/ , 2 /*業務線級別，2-所屬業務線，1-其他業務線*/ , map);
				}
				//console.log("MEMBER_NAME " + object.get('MEMBER_NAME'));
			}
			getat("man", 2);
			kfzxfm_toggle();
		} else {
			for (var i = 0; i < results.length; i++) {
				var object = results[i];

				if (object.get('PROD_ID') == prodid) {
					add_li(1 /*需要加入的li的個數*/ , switchProdName(object.get('PROD_ID')) /*需要加入的文本內容*/ , object.get('MEMBER_NAME') /*人名*/ , 2 /*業務線級別，2-所屬業務線，1-其他業務線*/ , map);
				} else {
					if (object.get('PROD_ID') != 4) { //过滤总体组
						add_li(1 /*需要加入的li的個數*/ , switchProdName(object.get('PROD_ID')) /*需要加入的文本內容*/ , object.get('MEMBER_NAME') /*人名*/ , 1 /*業務線級別，2-所屬業務線，1-其他業務線*/ , map);
					}
				}
				//console.log("MEMBER_NAME " + object.get('MEMBER_NAME'));
			}
			//			var prodid = sessionStorage.prodid;
			getat("spot", prodid == 1 ? 2 : 1);
			getat("forward", prodid == 2 ? 2 : 1);
			getat("plat", prodid == 3 ? 2 : 1);
			kfzxfm_toggle();
		}



	}, function(error) {
		hanlderError(error);
	});
}

function switchProdName(prod_id) {
	switch (parseInt(prod_id)) {
		case 1:
			return "spot";
			break;
		case 2:
			return "forward";
			break;
		case 3:
			return "plat";
			break;
		case 4:
			return "man";
			break;
		default:
			return "what";
			break;
	}
}

function submitEval(memberArr) {
//	for (var i = 0; i < memberArr.length; i++) {
//		updMembers(memberArr[i].name, memberArr[i].score, memberArr[i].content);
//	}
	/*for (var i = 0; i < memberArr.length; i++) {
		saveEvalDtl(memberArr[i].name, memberArr[i].score, memberArr[i].content);
	}*/
	saveEvalDtl(memberArr);
	//saveEvalDtl(memberArr);
	//setTimeout(updRegStatus(), 100);
	//updRegStatus();
}

function updRegStatus() {
	var query = new AV.Query(JRSC_REG);
	query.equalTo("REG_CODE", localStorage.regcode);
	query.find().then(function(results) {
		var obj = results[0];
		if (obj == undefined) {
			alert("登陆验证码不存在，请重新录入");
			localStorage.removeItem("regcode");
			localStorage.removeItem("evalstatus");
			return;
		}
		var eval_status = obj.get("EVAL_STATUS");
		if (eval_status == 0) {
			//localStorage.regcode = regcode;
			localStorage.setItem("evalstatus", "1");
			obj.set("EVAL_STATUS", 1);
			obj.save();
			//localStorage.evalstatus = eval_status;//完成评价后需要重写
//			location.href = "success.html";
		} else {
			//alert("您已经完成评价！");
			location.href = "done.html";
			//跳转到已评价的页面，只能查看评价结果，不能再做修改
		}
	}, function(error) {
		hanlderError(error);
	});
}

function updMembers(member, score, content) {
	var query = new AV.Query(JRSC_MEMBERS);
	query.equalTo("MEMBER_NAME", member);
	query.find({
		success: function(lists) {
			var obj = lists[0];
			var old_score = parseInt(obj.get("CROSS_SCORES"));
			obj.set("CROSS_SCORES", old_score + parseInt(score));
			obj.save();
		},
		error: function(error) {
			hanlderError(error);
		}
	});
}

function saveEvalDtl(memberArr) {
	var arr = new Array();
	//var eval_dtl = AV.Object.new('JRSC_EVAL_DTL');
	for (var i = 0; i < memberArr.length; i++) {
		var eval_dtl = AV.Object.new('JRSC_EVAL_DTL');
		eval_dtl.set("MEMBER_NAME", memberArr[i].name);
		eval_dtl.set("EVAL_SCORES", parseInt(memberArr[i].score));
		eval_dtl.set("EVAL_CONTETNS", memberArr[i].content);
		eval_dtl.set("EVAL_PROD_ID", sessionStorage.prodid == memberArr[i].pid?0:1);//评价人和被评价人相同业务线记0，否则记1
		eval_dtl.set("MEMBER_PROD_ID", memberArr[i].pid);
		arr[i] = eval_dtl;
	}
	AV.Object.saveAll(arr, {
		success: function(list) {
			console.log('评价明细success: ' + arr);
			location.href = "success.html";
		},
		error: function(error) {
			// An error occurred while saving one of the objects.
			console.log('评价明细error: ' + arr);
			localStorage.setItem("submit_code", "0");
			hanlderError(error);
		}
	});
	/*eval_dtl.save(null, {
		success: function(eval_dtl) {
			// 成功保存之后，执行其他逻辑.
			console.log('评价明细: ' + member);
		},
		error: function(eval_dtl, error) {
			// 失败之后执行其他逻辑
			// error 是 AV.Error 的实例，包含有错误码和描述信息.
			alert('保存评价明细失败: ' + error.message);
			console.log('评价明细: ' + member + " " + score + " " + content);
		}
	});*/
}

function checkRegcode(regcode) {
	var jrsc_reg = new AV.Query(JRSC_REG);
	jrsc_reg.equalTo("REG_CODE", regcode);
	jrsc_reg.first().then(function(obj) {
		if (obj == undefined) {
			alert("登陆验证码不存在，请重新录入");
		}
		var eval_status = obj.get("EVAL_STATUS");
		if (eval_status == 0) {
			localStorage.regcode = regcode;
			localStorage.evalstatus = eval_status; //完成评价后需要重写
			location.href = "choosebelong.html";
		} else {
			//alert("您已经完成评价！");
			location.href = "done.html";
			//跳转到已评价的页面，只能查看评价结果，不能再做修改
		}
	}, function(error) {
		hanlderError(error);
	});
}

function hanlderError(error) {
	console.log("错误代码：" + error.code + " 错误信息：" + error.message);
}

function kfzxfm_login() {
	var user = new AV.User();
	var username = document.getElementById("account").value;
	var password = document.getElementById("password").value;
	AV.User.logIn(username, password, {
		success: function(user) {
			location.href = "main.html";
		},
		error: function(user, error) {
			alert("Error: " + error.code + " " + error.message);
		}
	});
}

function kfzxfm_reg() {
	var user = new AV.User();
	var username = document.getElementById("account").value;
	var password = document.getElementById("password").value;
	var password_confirm = document.getElementById("password_confirm").value;
	var email = document.getElementById("email").value;
	if (password != password_confirm) {
		alert("两次密码输入不一致");
		return;
	}
	user.set("username", username);
	user.set("password", password);
	user.set("email", email);
	user.signUp(null, {
		success: function(user) {
			// 注册成功，可以使用了.
			alert("注册成功");
			location.href = "main.html";
		},
		error: function(user, error) {
			// 失败了
			alert("Error: " + error.code + " " + error.message);
		}
	});
}

function kfzxfm_logout() {
	AV.User.logOut();
	location.href = "index.html";
}


//生成可頭分數
//var num_man;

function show_num(n /*人數*/ , team /*業務線*/ , flag /*業務線級別，2-所屬業務線，1-其他業務線*/ ) {
	var per_belong = 0.6;
	var per_notbelong = 0.2;

	//				var per_other = ;
	var num_all;
	//	var num_other;
	if (flag == 2) {
		num_all = Math.round(n * per_belong);
	} else {
		num_all = Math.round(n * per_notbelong);
	}
	var span = document.getElementById(team + "_all_num");
	//				var span_last = document.getElementById("last_num");
	span.innerText = num_all;
	//				span_last.innerText = num_man;
}

//生成已投分數
function starbucks(name /*id名稱*/ , team /*業務線*/ , flag /*業務線級別，2-所屬業務線，1-其他業務線*/ , map) {
	//	var map = new Map();
	//	var num = sessionStorage.idnum;
	//	for (var k = num; k > num - n; k--) {
	var name = "#" + name;
	$(name).raty({
		number: flag,
		showCancel: true,
		onClick: function(score) {
			//											alert(window.event.srcElement.parentElement.id);
			var num = sessionStorage.idnum;
			var a = window.event.srcElement.parentElement.id;
			//				var new_name = "#" + a.slice(0, 10);
			//							alert(new_name);
			map.put(a, score);
			//				var m = 50; //循環個數
			var new_used_num = 0;
			//							alert(name);
			var team_1 = window.event.srcElement.parentElement.parentElement.parentElement.id;
			for (var l = 0; l < num + 1; l++) {
				var name1 = "star_" + team_1 + "_" + l;
				var value = map.get(name1);
				//								alert(new_used_num);
				//								alert(name1);
				//								alert(map.get(name1));
				if (value != null) {
					new_used_num = parseInt(new_used_num) + parseInt(value);
				}
				//								alert(new_used_num);
			}
			var span_used = document.getElementById(team + "_used_num");
			span_used.innerText = new_used_num;
		}
	});
	//	}
}

//生成人員名單

function add_li(n /*需要加入的li的個數*/ , team /*需要加入的文本內容*/ , name /*人名*/ , flag /*業務線級別，2-所屬業務線，1-其他業務線*/ , map) {
	var ul = document.getElementById(team);
	for (var i = 0; i < n; i++) {
		var li = document.createElement("li"); //創建list
		//							var t = document.createTextNode(text);//li的創建文本內容
		var div_img = document.createElement("div"); //創建背景圖片div
		var div_text = document.createElement("div"); //創建文本內容的div
		//							var span = document.createElement("span");//頭像圖片
		var text_area = document.createElement("textarea"); //文本輸入框
		var div_star = document.createElement("div");
		//			var m;//id順序號
		var idnum = sessionStorage.idnum; //順序號
		if (idnum != undefined) {
			//						li.id = team +idnum ;
			sessionStorage.idnum = parseInt(idnum) + 1;
		} else {
			sessionStorage.idnum = 0;
		}
		idnum = sessionStorage.idnum;
		li.id = team + idnum;

		div_img.className = "ui-avatar-s";
		div_img.innerHTML = "<span style='background-image:url(img/logo.jpg)'></span>";
		div_text.className = "ui-list-info ui-border-t";
		div_text.innerHTML = "<h4 class='fmer'>" + name + "</h4>";
		//							<textarea class='ui-input-wrap ui-border-t' style='display: none;'></textarea>
		text_area.id = "text_" + team + "_" + idnum;
		text_area.className = "ui-input-wrap ui-border-t";
		text_area.style.cssText = "display: none;width: 150px;";
		text_area.placeholder = "请输入评价....";
		//							<div id="star" style="display: none;"class="star ui-list-info ui-border-t"></div>
		div_star.id = "star_" + team + "_" + idnum;
		div_star.style.cssText = "display: none;";
		div_star.className = "star ui-list-info ui-border-t";
		//							alert(text);
		//							li.innerHTML="<div class='ui-avatar-s'><span style='background-image:url(img/logo.jpg)'></span></div><div class='ui-list-info ui-border-t'><h4>"+"name"+i+"</h4></div><textarea class='ui-input-wrap ui-border-t' style='display: none;'></textarea>";//添加li中要显示的内容
		li.appendChild(div_img); //創建頭像圖片
		div_text.appendChild(text_area); //
		li.appendChild(div_text); //創建文本
		li.appendChild(div_star); //
		//							li.appendChild(text_area);//創建文本輸入框
		ul.appendChild(li); //創建li
		//							alert(li.innerHTML);
		starbucks(div_star.id, team, flag, map);
	}
	//		starbucks(n, flag);
}

//獲取總人數，獲取磕頭分數
function getat(team, flag) {
		var ul_num = document.getElementById(team);
		//		alert(ul_num.getElementsByTagName("li").length);
		var n = ul_num.getElementsByTagName("li").length;
		//		starbucks(n, team, flag);
		show_num(n, team, flag);
		var span = document.getElementById(team + "_nums");
		span.innerText = n;
	}
	//校驗輸入數據是否正確

//提交
function preSubmit() {

	var prodid = sessionStorage.prodid;
	var evalstatus = localStorage.evalstatus;
//	location.href = "loading.html";
//	$("#submmit").attr("disabled",true);

	if (evalstatus == "1") {
		location.href = "done.html";
		return;
	}
	switch (parseInt(prodid)) {
		case 1:
			var spot_all_num = $("#spot_all_num").text();
			var forward_all_num = $("#forward_all_num").text();
			var plat_all_num = $("#plat_all_num").text();

			var spot_used_num = $("#spot_used_num").text();
			var forward_used_num = $("#forward_used_num").text();
			var plat_used_num = $("#plat_used_num").text();
			if (spot_all_num != spot_used_num) {
				alert("即期组内已评分数必须等于可评分数");
				return;
			}
			if (forward_all_num < forward_used_num) {
				alert("远期组外已评分数不能大于可评分数");
				return;
			}
			if (plat_all_num < plat_used_num) {
				alert("平台组外已评分数不能大于可评分数");
				return;
			}
			break;
		case 2:
			var spot_all_num = $("#spot_all_num").text();
			var forward_all_num = $("#forward_all_num").text();
			var plat_all_num = $("#plat_all_num").text();

			var spot_used_num = $("#spot_used_num").text();
			var forward_used_num = $("#forward_used_num").text();
			var plat_used_num = $("#plat_used_num").text();
			if (spot_all_num < spot_used_num) {
				alert("即期组内已评分数不能大于可评分数");
				return;
			}
			if (forward_all_num != forward_used_num) {
				alert("远期组外已评分数必须等于可评分数");
				return;
			}
			if (plat_all_num < plat_used_num) {
				alert("平台组外已评分数不能大于可评分数");
				return;
			}
			break;
		case 3:
			var spot_all_num = $("#spot_all_num").text();
			var forward_all_num = $("#forward_all_num").text();
			var plat_all_num = $("#plat_all_num").text();

			var spot_used_num = $("#spot_used_num").text();
			var forward_used_num = $("#forward_used_num").text();
			var plat_used_num = $("#plat_used_num").text();
			if (spot_all_num < spot_used_num) {
				alert("即期组内已评分数不能大于可评分数");
				return;
			}
			if (forward_all_num < forward_used_num) {
				alert("远期组外已评分数不能大于可评分数");
				return;
			}
			if (plat_all_num != plat_used_num) {
				alert("平台组外已评分数必须等于可评分数");
				return;
			}
			break;
		case 4:
			var man_all_num = $("#man_all_num").text();

			var man_used_num = $("#man_used_num").text();

			if (man_all_num != man_used_num) {
				alert("总体组内已评分数必须等于可评分数");
				return;
			}
			break;
		default:
			alert("别开玩笑了，你不属于任何组");
			return;
	}
	var members = new Array();
	var objArr = $("div").filter(".star");
	var len = objArr.length;
	//	alert(len);
	var j = 0;
	for (var i = 0; i < len; i++) {
		var obj = new Object();
		obj.name = $(objArr[i]).prev().children().eq(0).text();
		obj.content = $(objArr[i]).prev().children().eq(1).val();
		obj.score = $(objArr[i]).find("input[type=hidden]").val();
		var prdLine=$(objArr[i]).parent().parent().attr("id");
		if(prdLine==="spot"){
			obj.pid=1;
		}else if(prdLine==="forward"){
			obj.pid=2;
		}else if(prdLine==="plat"){
			obj.pid=3;
		}else if(prdLine==="man"){
			obj.pid=4;
		}else{}
		
		if (obj.score != 0) {
			if (obj.content == "") {
				alert("您还有已评分的成员未评价，请您评价完成后再提交，谢谢合作～");
				return;
			} else {
				members[j] = obj;
				j++;
			}
		}
	}
	//	$("div").filter(".star").each(function() {
	//
	//		//					alert($(this).prev().children().eq(0).text());
	//		//					alert($(this).prev().children().eq(1).val());
	//		//					alert($(this).find("input[type=hidden]").val());
	//		var obj = new Object();
	//		obj.name = $(this).prev().children().eq(0).text();
	//		obj.content = $(this).prev().children().eq(1).val();
	//		obj.score = $(this).find("input[type=hidden]").val();
	//		if (obj.score != 0) {
	//			if (obj.content == "") {
	//				alert("您还有已评分的成员未评价，请您评价完成后再提交，谢谢合作～");
	//			} else{
	//				members[i] = obj;
	//				i++;
	//			}
	//		}
	//	});
	//校驗完成後，需要做遮蔽處理，防止反覆輸入 linzr 20160113
	location.href = "loading.html";
	localStorage.setItem("submit_code", "1");//在本地存儲中寫入標誌，1表示當前正在提交中，控制不能再提交也不能後退 linzr 20160113
	submitEval(members);
	//	location.href = "success.html";
}

function kfzxfm_toggle() {
	var clicked;
	$(".fmer").on("click", function() {
		if (clicked != $(this).text()) {
			//					alert($(this).parent().next());
			//					$(".star").show();
			$(".fmer").next().hide();
			$(this).next().show();
			$(this).parent().next().show();
			clicked = $(this).text();
		} else {
			$(this).next().hide();
			clicked = 'inactive';
		}
	});
}

//測試數據
function test() {
	$("#submmit").prop("disabled",true);
//	$("#submmit").disabled=true;
}